package com.uduemc.biso.node.module.common.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.uduemc.biso.node.core.common.entities.Navigation;
import com.uduemc.biso.node.core.common.entities.publishdata.databody.LogoNavigation;
import com.uduemc.biso.node.core.common.entities.sitepage.PageType;
import com.uduemc.biso.node.core.common.siteconfig.SiteMenuConfig;
import com.uduemc.biso.node.core.entities.SCategories;
import com.uduemc.biso.node.core.entities.SConfig;
import com.uduemc.biso.node.core.entities.SNavigationConfig;
import com.uduemc.biso.node.core.entities.SPage;
import com.uduemc.biso.node.module.common.components.CSiteLink;
import com.uduemc.biso.node.module.common.service.CNavigationService;
import com.uduemc.biso.node.module.common.service.CSetService;
import com.uduemc.biso.node.module.service.SCategoriesService;
import com.uduemc.biso.node.module.service.SConfigService;
import com.uduemc.biso.node.module.service.SNavigationConfigService;
import com.uduemc.biso.node.module.service.SPageService;

@Service
public class CNavigationServiceImpl implements CNavigationService {

	@Autowired
	CSetService cSetServiceImpl;

	@Autowired
	SNavigationConfigService sNavigationConfigServiceImpl;

	@Autowired
	SPageService sPageServiceImpl;

	@Autowired
	SCategoriesService sCategoriesServiceImpl;

	@Autowired
	CSiteLink cSiteLink;

	@Autowired
	SConfigService sConfigServiceImpl;

	@Autowired
	ObjectMapper objectMapper;

	/**
	 * 为了提升性能问题，所以在循环遍历页面，生成页面的链接之前先把默认访问的第一个页面先找出来然后做对比
	 */
	@Override
	public List<Navigation> getInfosByHostSiteId(long hostId, long siteId) {

		SConfig sConfig = sConfigServiceImpl.findInfoByHostSiteId(hostId, siteId);

		// 获取当前site 的配置数据
		String menuConfig = sConfig.getMenuConfig();
		SiteMenuConfig siteMenuConfig = null;
		if (StringUtils.hasText(menuConfig)) {
			try {
				siteMenuConfig = objectMapper.readValue(menuConfig, SiteMenuConfig.class);
			} catch (IOException e) {
			}
		}
		if (siteMenuConfig == null) {
			siteMenuConfig = new SiteMenuConfig();
		}

		int maxIndex = siteMenuConfig.getMaxIndex();

		return getInfosByHostSiteId(hostId, siteId, maxIndex);
	}

	@Override
	public List<Navigation> getInfosByHostSiteId(long hostId, long siteId, int index) {
		// 获取页面数据
		List<SPage> listSPage = sPageServiceImpl.findSPageShowByHostSiteId(hostId, siteId,
				"`parent_id` ASC, `order_num` ASC, `id` ASC");

		SPage defaultPage = sPageServiceImpl.getDefaultPage(hostId, siteId);

		return getInfosByHostSiteId(listSPage, 0L, index, 0, defaultPage);
	}

	/**
	 * 
	 * @param listSPage    页面数据
	 * @param parentId     遍历的父级ID
	 * @param indexNum     遍历层次
	 * @param currentIndex 当前几层
	 * @param defaultPage  默认页面
	 * @return
	 */
	private List<Navigation> getInfosByHostSiteId(List<SPage> listSPage, long parentId, int indexNum, int currentIndex,
			SPage defaultPage) {
		List<Navigation> result = new ArrayList<>();
		if (indexNum < currentIndex) {
			return result;
		}

		Iterator<SPage> iterator = listSPage.iterator();
		while (iterator.hasNext()) {
			SPage sPage = iterator.next();
			if (sPage.getParentId() != null && sPage.getParentId().longValue() == parentId && sPage.getType() != null
					&& sPage.getType().shortValue() != (short) 0) {

				String target = StringUtils.isEmpty(sPage.getTarget()) ? "_self" : sPage.getTarget();

				Navigation navigation = new Navigation();
				navigation.setPageId(sPage.getId()).setTarget(target).setIndex(currentIndex);
				navigation.setText(sPage.getName()).setTitle(sPage.getName());

				if (sPage.getType().shortValue() == (short) 1) {
					// 普通页面
					navigation.setPageType(PageType.CUSTOM);
					// 构建链接
					String pageUri = null;
					if (defaultPage.getId().longValue() == sPage.getId().longValue()) {
						pageUri = "/index.html";
					} else {
						pageUri = cSiteLink.getPageUri(sPage);
					}
					navigation.setLink(pageUri);
					// 获取子页面.
					List<Navigation> listNavigation = getInfosByHostSiteId(listSPage, sPage.getId(), indexNum,
							currentIndex + 1, defaultPage);
					navigation.setChildren(listNavigation);

				} else if (sPage.getType().shortValue() == (short) 2) {
					// 系统页面
					navigation.setPageType(PageType.LIST);
					navigation.setSystemId(sPage.getSystemId());
					// 构建链接
					String pageUri = null;
					if (defaultPage.getId().longValue() == sPage.getId().longValue()) {
						pageUri = "/index.html";
					} else {
						pageUri = cSiteLink.getPageUri(sPage);
					}
					navigation.setLink(pageUri);
					String orderBy = "`parent_id` ASC, `order_num` ASC, `id` ASC";
					List<SCategories> listSCategories = sCategoriesServiceImpl.findByHostSiteSystemIdPageSizeOrderBy(
							sPage.getHostId(), sPage.getSiteId(), sPage.getSystemId(), orderBy);
					List<Navigation> listNavigation = getSystemInfosByHostSiteId(sPage, listSCategories, 0L,
							indexNum - currentIndex, currentIndex + 1);
					navigation.setChildren(listNavigation);
				} else if (sPage.getType().shortValue() == (short) 3) {
					// 外部链接导航
					navigation.setPageType(PageType.EXTERNAL_LINK);
					// 构建链接
					String pageUri = cSiteLink.getPageUri(sPage);
					navigation.setLink(pageUri);
					// 获取子页面.
					List<Navigation> listNavigation = getInfosByHostSiteId(listSPage, sPage.getId(), indexNum,
							currentIndex + 1, defaultPage);
					navigation.setChildren(listNavigation);
				} else if (sPage.getType().shortValue() == (short) 4) {
					// 内部链接导航
					navigation.setPageType(PageType.INSIDE_LINK);
					// 构建链接
					String pageUri = cSiteLink.getPageUri(sPage);
					navigation.setLink(pageUri);
					// 获取子页面.
					List<Navigation> listNavigation = getInfosByHostSiteId(listSPage, sPage.getId(), indexNum,
							currentIndex + 1, defaultPage);
					navigation.setChildren(listNavigation);
				} else {
					throw new RuntimeException("未知的页面类型无法构建页面链接！");
				}
				result.add(navigation);
			}
		}
		return result;
	}

	/**
	 * 系统分类生成的导航栏目
	 * 
	 * @param sPage           系统页面
	 * @param listSCategories 整个系统的分类数据
	 * @param parentId        开始的父级id
	 * @param indexNum        几层
	 * @param currentIndex    当前第几层
	 * @return
	 */
	private List<Navigation> getSystemInfosByHostSiteId(SPage sPage, List<SCategories> listSCategories, long parentId,
			int indexNum, int currentIndex) {
		List<Navigation> result = new ArrayList<>();
		if (indexNum <= currentIndex) {
			return result;
		}
		Iterator<SCategories> iterator = listSCategories.iterator();
		while (iterator.hasNext()) {
			SCategories sCategories = iterator.next();
			if (sCategories.getParentId() != null && sCategories.getParentId().longValue() == parentId) {

				String target = StringUtils.isEmpty(sCategories.getTarget()) ? "_self" : sCategories.getTarget();

				Navigation navigation = new Navigation();
				navigation.setPageId(sPage.getId()).setTarget(target).setIndex(currentIndex);
				navigation.setText(sCategories.getName()).setTitle(sCategories.getName());

				navigation.setPageType(PageType.LIST);
				navigation.setCategoryId(sCategories.getId()).setSystemId(sPage.getSystemId());
				// 构建链接
				String pageUri = cSiteLink.getCagetoryUri(sPage, sCategories);
				navigation.setLink(pageUri);
				// 获取子页面.
				List<Navigation> listNavigation = getSystemInfosByHostSiteId(sPage, listSCategories,
						sCategories.getId(), indexNum, currentIndex + 1);
				navigation.setChildren(listNavigation);
				result.add(navigation);
			}
		}
		return result;
	}

	@Override
	@Transactional
	public void publish(long hostId, long siteId, LogoNavigation snavigation) {
		SConfig sConfig = sConfigServiceImpl.findInfoByHostSiteId(hostId, siteId);
		if (sConfig == null) {
			throw new RuntimeException("通过 hostId、siteId 获取 sConfig 数据失败 hostId、siteId： " + hostId + "、" + siteId);
		}
		if (snavigation == null) {
			return;
		}
		String menuConfig = snavigation.getMenuConfig();
		sConfig.setMenuConfig(menuConfig);
		sConfigServiceImpl.updateById(sConfig);

		try {
			SiteMenuConfig siteMenuConfig = objectMapper.readValue(menuConfig, SiteMenuConfig.class);
			if (siteMenuConfig != null && siteMenuConfig.getMaxIndex() > 0) {
				SNavigationConfig sNavigationConfig = sNavigationConfigServiceImpl
						.findByHostSiteIdAndNoDataCreate(hostId, siteId);
				if (sNavigationConfig != null) {
					sNavigationConfig.setIndexNum(siteMenuConfig.getMaxIndex()).setConf(menuConfig);
					sNavigationConfigServiceImpl.updateById(sNavigationConfig);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
